package com.heima.media.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.media.entity.WmSensitive;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmSensitiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private IAuditService auditService;

    @GetMapping("/audit/{id}")
    public ResponseResult audit(@PathVariable("id") Integer id) {
        auditService.audit(id);
        return ResponseResult.okResult();
    }

    @Autowired
    private IWmSensitiveService sensitiveService;

    @PostMapping("/upload")
    public ResponseResult upload(MultipartFile file) throws Exception {
//        解析excel 并导入数据
        EasyExcel.read(file.getInputStream(), WmSensitive.class,new PageReadListener<WmSensitive>(dataList->{
            for (WmSensitive sensitive : dataList) {
//                查询目前表中是否有这个敏感词
                LambdaQueryWrapper<WmSensitive>  queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WmSensitive::getSensitives,sensitive.getSensitives());
                int count = sensitiveService.count(queryWrapper);
                if(count==0){
                    sensitive.setCreatedTime(new Date());
                    sensitiveService.save(sensitive);
                }
            }

        })).sheet().doRead();
        return ResponseResult.okResult("成功");
    }


    @PostMapping("/download")
    public ResponseResult download(HttpServletResponse response) throws Exception {
        List<WmSensitive> list = sensitiveService.list();
//        一个流两个头  流：文件的输出流 两个头：文件的mine类型和打开方式
        response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode("sensitive.xlsx", "UTF-8"));
//        response.setHeader("Content-type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        EasyExcel.write(response.getOutputStream(),WmSensitive.class)
                .sheet("敏感词")
                .doWrite(list);

        return ResponseResult.okResult("成功");
    }
}
